package com.ghh.app.photoframe;

import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PhotoFrame {
	private final static String	PREFERENCE_NAME	= "com.ghh.photoframe";

	private int					appWidgetId;
	private String				preference_name_images;
	private String				preference_name_index;

	private Context				context;
	private Set<String>			imageSet;
	private int					currentIndex	= 0;

	public PhotoFrame(int appWidgetId, Context context) {
		this.appWidgetId = appWidgetId;
		this.context = context;
		preference_name_images = PREFERENCE_NAME + ".images." + appWidgetId;
		preference_name_index = PREFERENCE_NAME + ".index." + appWidgetId;
		init();
	}

	private void init() {
		SharedPreferences preference = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
		imageSet = preference.getStringSet(preference_name_images, null);
		currentIndex = preference.getInt(preference_name_index, 0);
	}

	public void save() {
		SharedPreferences preference = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
		Editor editor = preference.edit();
		editor.putStringSet(preference_name_images, imageSet);
		editor.putInt(preference_name_index, currentIndex);
		editor.commit();
	}

	public boolean exist() {
		SharedPreferences preference = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
		return preference.contains(preference_name_images);
	}
	
	public String getCurrentPhoto() {
		if (imageSet == null) {
			return null;
		}
		Iterator<String> it = imageSet.iterator();
		int i = 0;
		int size = imageSet.size();
		while (it.hasNext()) {
			String s = it.next();
			if (i == currentIndex % size) {
				return s;
			}
			i++;
		}
		return null;
	}

	public void remove() {
		SharedPreferences preference = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
		Editor editor = preference.edit();
		editor.remove(preference_name_images);
		editor.remove(preference_name_index);
		editor.commit();
	}

	public int getAppWidgetId() {
		return appWidgetId;
	}

	public void setAppWidgetId(int appWidgetId) {
		this.appWidgetId = appWidgetId;
	}

	public Set<String> getImageSet() {
		return imageSet;
	}

	public void setImageSet(Set<String> imageSet) {
		this.imageSet = imageSet;
	}

	public int getCurrentIndex() {
		return currentIndex;
	}

	public void setCurrentIndex(int currentIndex) {
		this.currentIndex = currentIndex;
	}
}
